import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import 'dart:convert' as convert;
import 'package:dio/dio.dart';
import '../models/index.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  int _counter = 0;
  String _clientId = 'Unknown';

  String _imServerHost = "chat.digintech.cn";
  int _imServerPort = 80;

  String _appServerHost = "chat.digintech.cn";
  int _appServerPort = 8888;

  // String _imServerHost = "wildfirechat.cn";
  // int _imServerPort = 80;
  // String _appServerHost = "wildfirechat.cn";
  // int _appServerPort = 8888;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    await FlutterWildfire.init(_imServerHost, _imServerPort);
    FlutterWildfire.on("receiveMessage", (messages) {
      print('receiveMessage');
      print(messages);
    });
  }

  void onPressed() async {
    String clientId;
    Response response;
    Dio dio = new Dio();
    try {
      clientId = await FlutterWildfire.getClientId();
      String _loginUrl = 'https://$_appServerHost:$_appServerPort/login';
      // var res = await client.post(_loginUrl,
      //     headers: {
      //       'content-type': 'application/json',
      //     },
      //     body: convert.jsonEncode({
      //       'clientId': clientId,
      //       'mobile': '15367680311',
      //       'code': '66666'
      //     }));
      response = await dio.post(_loginUrl, data: {
        "clientId": clientId,
        "mobile": "15367680311",
        'code': '66666'
      });
      if (response.data['code'] != 0) {
        throw response.data['message'];
      }
      LoginResult result = LoginResult.fromJson(response.data['result']);

      // var json = convert.jsonDecode(response.data);
      print(response.data.toString());
      var userId = result.userId;
      var token = result.token;
      await FlutterWildfire.connect(userId, token);
    } catch (e) {
      clientId = 'Failed to get client id.';
      print('error');
    } finally {
      // clientId = 'Failed to get client id.';
      // client.close();
    }
    setState(() {
      _counter++;
      _clientId = clientId;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: ListView(
          reverse: false,
          children: <Widget>[
            new MaterialButton(
              color: Colors.blue,
              textColor: Colors.white,
              child: new Text('login'),
              onPressed: onPressed,
            ),
            new MaterialButton(
              color: Colors.blue,
              textColor: Colors.white,
              child: new Text('getConversationList'),
              onPressed: () async {
                
                var clientId = await FlutterWildfire.getClientId();
                var result =
                    await FlutterWildfire.getConversationList(['Single'], [0]);
                print(result);
              },
            ),
            new MaterialButton(
              color: Colors.blue,
              textColor: Colors.white,
              child: new Text('getConversation UZU7U7oo'),
              onPressed: () async {
                var result = await FlutterWildfire.getConversation(
                    'Single', 'UZU7U7oo', 0);
                print(result);
              },
            ),
            
          ],
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: onPressed,
          tooltip: 'Increment',
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}
